package com.cat.dataStructure;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-score-from-removing-substrings/description/
 * @create 2025/9/9 14:53
 * @since JDK17
 */

public class Solution67 {
    int ans;
    // 删ab
    String f1(char[] s, int x) {
        int n = s.length, top = 0;
        char[] stack = new char[n];
        for (int i = 0; i < n; i++) {
            if (top == 0 || !(s[i] == 'b' && stack[top - 1] == 'a')) {
                stack[top++] = s[i];
            } else {
                top--;
                ans += x;
            }
        }
        return new String(stack, 0, top);
    }
    String f2(char[] s, int x) {
        int n = s.length, top = 0;
        char[] stack = new char[n];
        for (int i = 0; i < n; i++) {
            if (top == 0 || !(s[i] == 'a' && stack[top - 1] == 'b')) {
                stack[top++] = s[i];
            } else {
                top--;
                ans += x;
            }
        }
        return new String(stack, 0, top);
    }


    public int maximumGain(String s, int x, int y) {
        if (x > y) {
            s = f1(s.toCharArray(), x);
            s = f2(s.toCharArray(), y);
        } else {
            s = f2(s.toCharArray(), y);
            s = f1(s.toCharArray(), x);
        }
        return ans;
    }
}
